<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="120px">
          <el-form-item label="课程名称" prop="courseId">
            <el-input v-model="queryParams.courseName" placeholder="请输入" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="学段" prop="coursePeriod">
            <!-- <el-input v-model="queryParams.coursePeriod" placeholder="请输入学段" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <el-select v-model="queryParams.coursePeriod" placeholder="请输入" clearable>
              <el-option v-for="dict in sys_period" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="年级(班级)" prop="courseGrade">
            <el-input v-model="queryParams.courseGrade" placeholder="请输入年级(班级)" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="学科" prop="courseSubject">
            <el-input v-model="queryParams.courseSubject" placeholder="请输入" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="地区" prop="courseArea">
            <el-input v-model="queryParams.courseArea" placeholder="请输入" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="学校" prop="courseDept">
            <!-- <el-input v-model="queryParams.courseDept" placeholder="请输入" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <!-- <el-tree-select
            filterable
            clearable
            v-model="queryParams.courseDept"
            :data="deptOptions"
            :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
            value-key="deptId"
            placeholder="请选择学校"
            :render-after-expand="false"
          /> -->
            <el-select v-model="queryParams.courseDept" placeholder="请选择学校" clearable :disabled="!(userId === 1 && tenantDisabled)">
              <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="授课时间" prop="courseDate">
            <el-date-picker
              clearable
              v-model="queryParams.courseDate"
              type="date"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="年/月/日"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="handleAdd" v-hasPermi="['core:testTimeTable:add']">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>
    <!--日历表  -->
    <el-card shadow="never">
    <template #header>
      <h2>实验排课管理</h2>
    </template>
    <div class="table-header">
      <el-tag type="info">
        {{ currentWeekRange[0] + '至' + currentWeekRange[1] }}
      </el-tag>
      <div class="center">
        <el-button @click="weekPre"> <i class="el-icon-arrow-left"></i>上一周 </el-button>
        <p>{{ currentYear }}年{{ currentMonth }}月</p>
        <el-button @click="weekNext"> 下一周<i class="el-icon-arrow-right"></i> </el-button>
      </div>
    </div>
    <el-card shadow="never">
      <!-- 表标题 -->
      <table align="center" cellpadding="0" cellspacing="0">
        <tr class="special">
          <td>
            <el-icon :size="20" @click="dialogVisible = true" style="cursor: pointer; margin-bottom: 20px"><Calendar /></el-icon>
          </td>
          <!-- 周 -->
          <td v-for="(item, index) in weekGround" :key="index" class="special-cell">{{ item }}</td>
        </tr>

        <tr v-for="(item, index) in timeGround" :key="index">
    <!-- 课程时间轴 -->
    <td class="time">{{ index +1}}</td>
    <!-- 第几周 -->
    <td
      align="center"
      valign="middle"
      v-for="(dayCourses, index1) in course"
      :key="index1"
    >
      <!-- 检查当天是否有课程 -->
      <div v-if="dayCourses.length > 0">
        <!-- 遍历当天的所有课程 -->
        <div
          class="course-item"
          v-for="(courseItem, index2) in dayCourses"
          :key="index2"
          @click="handleView(courseItem)"
          :style="{ backgroundColor:coachColorMap[courseItem.subjectName]? hexToRgba(coachColorMap[courseItem.subjectName], 0.4) :hexToRgba(colorList[index2], 0.4) }"
        >
          <!-- <p :style="{ color: coachColorMap[courseItem.subjectName] }">{{ courseItem.courseName }}</p>
          <p :style="{ color: coachColorMap[courseItem.subjectName] }">{{ courseItem.subjectName }}</p> -->
          <p :style="{ color: coachColorMap[courseItem.subjectName]?hexToRgba(coachColorMap[courseItem.subjectName]):hexToRgba(colorList[index2]) }">{{ courseItem.courseName }}</p>
          <p :style="{ color: coachColorMap[courseItem.subjectName]?hexToRgba(coachColorMap[courseItem.subjectName]):hexToRgba(colorList[index2])}">{{ courseItem.subjectName }}</p>
        </div>
      </div>
      <!-- 如果当天没有任何课程，则显示 "+" 号 -->
      <div v-else class="course-item" @click="handleAdd">
        +
      </div>
    </td>
  </tr>
      </table>
    </el-card>
    <el-dialog v-model="dialogVisible" title="选择日期">
      <el-date-picker v-model="queryParams.courseDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择授课时间" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCourse">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
    <!--  -->
    <!-- 添加或修改实验课程对话框 -->
        <!-- 添加或修改实验目录对话框 -->
      <ListBord ref="testTeachRef" />
  </div>
</template>

<script setup name="TestTimeTable" lang="ts">
import {
  listTestTimeTableCard,
  listTestTimeTable,
  getTestTimeTable,
  delTestTimeTable,
  addTestTimeTable,
  updateTestTimeTable
} from '@/api/core/testTimeTable';
import { TestTimeTableVO, TestTimeTableQuery, TestTimeTableForm } from '@/api/core/testTimeTable/types';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_yes_no, sys_period } = toRefs<any>(proxy?.useDict('sys_yes_no', 'sys_period'));
const testTimeTableList = ref<TestTimeTableVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
import ListBord from './listBord.vue';
const testTeachRef = ref<InstanceType<typeof listBord>>();
  import { useSchoolList } from '@/composables/useSchoolList';
  const { deptOptions, fetchSchoolList } = useSchoolList();
import { formatDate as format } from '@/utils/index';
const queryFormRef = ref<ElFormInstance>();
const testTimeTableFormRef = ref<ElFormInstance>();
//学校改租户数据
import { useTenantlList } from '@/composables/useSchoolList';
const { tenantOptions, fetchTenantlList,tenantDisabled} = useTenantlList();
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantId = ref(userStore.tenantId)

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialogVisible = ref(false);
const initFormData: TestTimeTableForm = {
  courseName: undefined,
  courseId: undefined,
  coursePeriod: undefined,
  courseGrade: undefined,
  courseSubject: undefined,
  courseArea: undefined,
  courseDept: undefined,
  courseDate: undefined,
  courseDateEnd:undefined,
};
const data = reactive<PageData<TestTimeTableForm, TestTimeTableQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: undefined,
    pageSize: undefined,
    courseName: undefined,
    courseId: undefined,
    coursePeriod: undefined,
    courseGrade: undefined,
    courseSubject: undefined,
    courseArea: undefined,
    courseDept: undefined,
    courseDate: undefined,
    courseDateEnd:undefined,
    
    params: {}
  },
  rules: {
    courseId: [{ required: true, message: '课程不能为空', trigger: 'blur' }],
    coursePeriod: [{ required: true, message: '学段不能为空', trigger: 'change' }],
    courseGrade: [{ required: true, message: '年级(班级)不能为空', trigger: 'blur' }],
    courseSubject: [{ required: true, message: '学科不能为空', trigger: 'blur' }],
    courseArea: [{ required: true, message: '授课地区不能为空', trigger: 'blur' }],
    courseDept: [{ required: true, message: '授课学校不能为空', trigger: 'blur' }],
    courseDate: [{ required: true, message: '授课开始时间不能为空', trigger: 'blur' }],
    courseDateEnd: [{ required: true, message: '授课结束时间不能为空', trigger: 'blur' }],
  }
});

const { queryParams, form, rules } = toRefs(data);
interface Course {
  id: number;
  courseId: number;
  courseName: string;
  coursePeriod: string;
  courseGrade: string;
  courseSubject: number;
  courseArea: number;
  courseDate: string;
  courseDateEnd: string;
  courseDept: number;
  deptName: string;
  subjectName: string;
  coach: string;
  title: string;
}

// 初始化数据
const weekGround = ref(['周一', '周二', '周三', '周四', '周五', '周六', '周日']);

const course = ref<Array<Array<Course>>>([]);
const currentYear = ref(0);
const currentMonth = ref(0);
const Now = ref(0);
const currentWeek = ref(0);
const days = ref<Date[]>([]);
const currentWeekRange = ref<string[]>([]);
const coachColorMap = reactive<{ [key: string]: string }>({
  英语: '#5974c0',
  数学: '#521262',
  语文: '#20822a'
});

const coachColorMap1 = ref({
  CoachA: '#ff0000', // 红色
  CoachB: '#00ff00', // 绿色
  CoachC: '#0000ff' // 蓝色
});
const colorList = ref([
  '#5974c0',
  '#521262',
  '#20822a',
  "#b8d38f",//马卡龙抹茶奶霜
  "#ddff95",//开心果杏仁饼
  "#f1f1b8",//杏仁饼黄
  "#f1ccb8",//杏仁饼橙
  "#b8f1cc",//杏仁饼绿
  "#b8f1ed",//杏仁饼海洋蓝
  "#e7dbca",//马卡龙枫武
  "#f1b8f1",//马卡龙粉
  "#d9b8f1",//杏仁饼紫
  "#f1ccb8",//盐焦仁糖杏饼
  "#cb8e85",//巧克力马卡龙
  "#fd803a",//马卡龙玫瑰果
])
const courseItem = ref({ coach: 'CoachA' }); // 示例课程项

// 方法：将十六进制颜色值转换为带有透明度的 rgba 值
const hexToRgba = (hex, opacity) => {
  hex = hex.replace('#', '');
  const r = parseInt(hex.substring(0, 2), 16);
  const g = parseInt(hex.substring(2, 4), 16);
  const b = parseInt(hex.substring(4, 6), 16);
  return `rgba(${r}, ${g}, ${b}, ${opacity})`;
};
// 日历选择
const addCourse = () => {
  updateDateAndFetchList(queryParams.value.courseDate);
  // 关闭对话框
  dialogVisible.value = false;
};

const formatDate = (year: number, month: number, day: number) => {
  const y = year;
  let m = month < 10 ? `0${month}` : month;
  let d = day < 10 ? `0${day}` : day;
  return `${y}-${m}-${d}`;
};

const initData = (cur?: Date) => {
  const date = cur ? new Date(cur) : new Date();
  Now.value = date.getDate();
  currentYear.value = date.getFullYear();
  currentMonth.value = date.getMonth() + 1;
  currentWeek.value = date.getDay();
  if (currentWeek.value === 0) {
    currentWeek.value = 7;
  }
  const str = formatDate(currentYear.value, currentMonth.value, Now.value);

  days.value.length = 0;
  for (let i = currentWeek.value - 1; i >= 0; i -= 1) {
    const d = new Date(str);
    d.setDate(d.getDate() - i);
    days.value.push(d);
  }
  for (let i = 1; i <= 7 - currentWeek.value; i += 1) {
    const d = new Date(str);
    d.setDate(d.getDate() + i);
    days.value.push(d);
  }

  currentWeekRange.value = [
    formatDate(days.value[0].getFullYear(), days.value[0].getMonth() + 1, days.value[0].getDate()),
    formatDate(days.value[6].getFullYear(), days.value[6].getMonth() + 1, days.value[6].getDate())
  ];
  const currentDayNow = new Date();
  const currentDate = `${currentDayNow.getMonth() + 1}/${currentDayNow.getDate()}`;
  const dataArr = days.value.map((item) => `${item.getMonth() + 1}/${item.getDate()}`);
  weekGround.value = weekGround.value.map((item, index) => {
    const [dayOfWeek, ...rest] = item.split(' ');
    const lastDate = rest.pop(); // 获取最后一个日期部分
    const newRest = rest.length > 0 ? rest.join(' ') : ''; // 处理剩余部分

    const formattedDate = dataArr[index];
    const isToday = formattedDate === currentDate;
    return `${dayOfWeek} ${newRest} (${dataArr[index]})`.trim();
  });
};

const weekPre = () => {
  const d = days.value[0];
  d.setDate(d.getDate() - 7);
  updateDateAndFetchList(format(d, 'yyyy-MM-dd'));
};

const weekNext = () => {
  const d = days.value[6];
  d.setDate(d.getDate() + 7);
  updateDateAndFetchList(format(d, 'yyyy-MM-dd'));
};

// 封装初始化数据和获取课程列表的方法
const updateDateAndFetchList = (dateStr: string) => {
  // 确保 dateStr 是一个有效的日期字符串
  // if (typeof dateStr !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
  //   console.error("Invalid date string:", dateStr);
  //   return;
  // }

  const date = new Date(dateStr);
  if (isNaN(date.getTime())) {
    console.error('Invalid date:', date);
    return;
  }

  queryParams.value.courseDate = dateStr;
  initData(date);
  getList();
};
const timeGround  = computed(() => {return Array.from({ length: Math.max(...maxCoursesPerDay.value) }, (_, i) => i);});

  const maxCoursesPerDay = computed(() => {
  return course.value.map(dayCourses => dayCourses.length);
});
// 生成时间轴
// const timeGround = 
const getList = async () => {
    loading.value = true;
    const res = await listTestTimeTableCard(queryParams.value);
    course.value=res
    loading.value = false;
};

onMounted(() => {
  const today = new Date();
  // queryParams.value.courseDate = today.toISOString().split("T")[0];
  queryParams.value.courseDate = format(today);
  initData(today);
  if(!(userId.value === 1 && tenantDisabled.value)){
    // queryParams.value.courseDept = getTenantById(tenantOptions.value,tenantId.value)
    queryParams.value.courseDept = Number(tenantId.value) ;
  }
  getList();
});

/*** 查看按钮 */
/** 查看按钮操作 */
const handleView = async (row?: TestTimeTableVO) => {
  // const id = row?.courseId || ids.value[0]
  
   if (testTeachRef.value) {
    testTeachRef.value.openDialog(row);
  }
}
/*** 新增按钮 */
const handleAdd = () => {
  router.push({ path: '/couto/testTimeTable/panel/', query: { type: 0 } });
};
/*** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};
/*** 重置表单 */
const reset = () => {
  form.value = { ...initFormData };
  testTimeTableFormRef.value?.resetFields();
};
/*** 搜索按钮 */
const handleQuery = () => {
  if (queryParams.value.courseDate) {
    initData(queryParams.value.courseDate);
    getList();
  }else{
    const today = new Date();
  // queryParams.value.courseDate = today.toISOString().split("T")[0];
  queryParams.value.courseDate = format(today);
  initData(today);
  getList();
  }
 
};
/*** 重置按钮 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
/*** 勾选按钮 */
const handleSelectionChange = (selection: TestTimeTableVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/*** 修改按钮 */
const handleUpdate = async (row?: TestTimeTableVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTestTimeTable(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改实验课程';
};
/*** 提交按钮 */
const submitForm = () => {
  testTimeTableFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (form.value.id) {
          await updateTestTimeTable(form.value);
        } else {
          await addTestTimeTable(form.value);
        }
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      } catch (error) {
        console.error('Submit failed:', error);
        proxy?.$modal.msgError('操作失败，请稍后再试');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};
/*** 删除按钮 */
const handleDelete = async (row?: TestTimeTableVO) => {
  const _ids = row?.id || ids.value;
  try {
    await proxy?.$modal.confirm(`是否确认删除实验课程编号为"${_ids}"的数据项？`);
    await delTestTimeTable(_ids);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
  } catch (error) {
    console.error('Delete failed:', error);
    proxy?.$modal.msgError('删除失败，请稍后再试');
  }
};

const handleExport = () => {
  proxy?.download('core/testTimeTable/export', { ...queryParams.value }, `testTimeTable_${new Date().getTime()}.xlsx`);
};
</script>
<style lang="scss" scoped>
/* 设置表格的基本样式 */
table {
  width: 100%;
  background-color: #fff;
  // border-color: #e3e8ee;
  text-align: center;
  border-radius: 4px;
  //  border-top: 1px solid #e3e8ee;
  // border-left: 1px solid #e3e8ee;
}
tr {
  border: none;
  text-align: center;
}
td {
  // border-bottom: 1px solid #e3e8ee;
  // border-right: 1px solid #e3e8ee;
  text-align: center;
  box-sizing: border-box;
}
/* 加号图标的样式 */
.plus-icon {
  font-size: 1rem;
  cursor: pointer;
}

/* 特殊单元格的样式 */
.special-cell {
  width: 120px;
  padding-bottom: 20px;
}
td:nth-child(1) {
  width: 30px !important;
}
.time-box {
  width: 160px !important;
}
tr:nth-child(1) {
  height: 30px;
  background-color: none !important;
  border: none;
  color: #525252;
  font-weight: bold;
}

tr:first-child {
  width: 50px;
  // background: #f7f7f7;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  box-sizing: border-box;
  padding: 0 10px;
  .center {
    display: flex;
    justify-content: center;
    align-items: center;
    p {
      font-size: 20px;
      margin: 0 30px;
    }
  }
}
.course-item {
  cursor: pointer;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  background: #f0f1f3;
  border-radius: 4px;
  box-sizing: border-box;
  margin: 1px;
  height: 120px;

  p {
    color: #fff;
  }
}
.time {
  color: #707070;
  font-weight: bold;
}
</style>

